#!/usr/bin/env python
# encoding=utf-8
import datetime
import re
from utility import tail
import sys

#解析# Time:行
def set_datetime_by_time_line(eventDic, line):
    #在解析新的单元之前清空字典
    eventDic.clear()
    time_str = "20" + line.replace("# Time:", "").replace("  ", " ").strip()
    query_time = datetime.datetime.strptime(time_str, "%Y%m%d %H:%M:%S")
    eventDic['time'] = query_time

#解析Query_time:行
def set_query_info(eventDic, line):
    tmp_line = line.replace("#", "").replace(": ", ":").replace("  ", " ").replace("  ", " ")
    tmp_items = tmp_line.split(" ")
    for tmp_item in tmp_items:
        # print(tmp_item)
        if tmp_item.strip().startswith("Query_time:"):
            eventDic['query_time'] = tmp_item.replace("Query_time:", "")
        if tmp_item.strip().startswith("Lock_time:"):
            eventDic['lock_time'] = tmp_item.replace("Lock_time:", "")
        if tmp_item.strip().startswith("Rows_sent:"):
            eventDic['rows_sent'] = tmp_item.replace("Rows_sent:", "")
        if tmp_item.strip().startswith("Rows_examined:"):
            eventDic['rows_examined'] = tmp_item.replace("Rows_examined:", "")

#解析user & ip
def set_login_user_ip(eventDic, line):
    tmp_line = line.replace("#", "").replace(": ", ":").replace("  ", " ").replace("  ", " ")
    result = re.findall("(\:)", tmp_line)
    eventDic['user'] = result[0]
    eventDic['ip'] = result[1]

#解析schema
def set_schema_error_killed(eventDic, line):
    tmp_line = line.replace("#", "").replace(": ", ":").replace("  ", " ").replace("  ", " ")
    # print(tmp_line)
    result = re.findall(":([\S]+)", tmp_line)
    eventDic['schema'] = result[0]
    eventDic['last_errno'] = result[1]
    eventDic['killed'] = result[2]

#解析bytes_sent
def set_bytes_sent(eventDic, line):
    tmp_line = line.replace("#", "").replace(": ", ":").replace("  ", " ").replace("  ", " ")
    # print(tmp_line)
    result = re.findall(":([\S]+)", tmp_line)
    eventDic['bytes_sent'] = result[0]

#解析sql行
def set_sql(eventDic, line, tmpSQL, events):
    if line.find(';') != -1:
        tmpSQL.append(line)
        #sql拼接为字符串
        fullSQL="".join(tmpSQL)
        print(fullSQL)
        eventDic['sql'] = tmpSQL
        #拼接完sql生成fingerprint

        #解析完成发送到server端并清空字典和拼接sql的list
        eventDic={}
        tmpSQL = []
    else:
        tmpSQL.append(line)

#解析timestamp
def set_timestamp(eventDic, line):
    result = re.findall("=([\S]+);", line)
    eventDic['timestamp'] = result[0]

#回调函数
def paserQueryLog(line, eventDic, tmpSQL):
    if line.startswith("# Time:"):
        set_datetime_by_time_line(eventDic, line)
    elif line.startswith("# Query_time:"):
        set_query_info(eventDic, line)
    elif line.startswith("# User@Host:"):
        set_login_user_ip(eventDic, line)
    elif line.startswith("# Schema:"):
        set_schema_error_killed(eventDic, line)
    elif line.startswith("# Bytes_sent:"):
        set_bytes_sent(eventDic, line)
    elif line.startswith("SET timestamp"):
        set_timestamp(eventDic, line)
    else:
        set_sql(eventDic, line, tmpSQL)


if __name__ == '__main__':
    t = tail.Tail('/opt/app/percona_3306/logs/slow.log')
    t.register_callback(paserQueryLog)
    t.follow(s=5)